package com.flca.dbs.berkeley;

import java.util.Iterator;

import com.flca.frw.dao.Dao;
import com.flca.frw.dao.PersistenceType;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;

public class BerkeleyDaoImpl implements Dao {

	private static final long serialVersionUID = 6859145331274345648L;

	private DaoHelperBerkeleyBase berkeleyBase;

	public BerkeleyDaoImpl() {
	}

	public BerkeleyDaoImpl(DaoHelperBerkeleyBase aBerkeleyBase) {
		berkeleyBase = aBerkeleyBase;
	}

	public Object getObjectMgr() {
		return berkeleyBase;
	}

	public boolean isInTransaction() throws Exception {
		if (getEnv() != null && getEnv().getThreadTransaction() != null) {
			return getEnv().getThreadTransaction().getPrepared();
		}
		return false;
	}

	public void commit() throws Exception {
		if (getEnv() != null && isInTransaction()) {
			getEnv().getThreadTransaction().commit();
		} else {
			// logError("commit called with EntityManager null");
		}
	}

	public void rollback() throws Exception {
		if (getEnv() != null && isInTransaction()) {
			getEnv().getThreadTransaction().abort();
		} else {
			logError("rollback called with EntityManager null");
		}
	}

	public void startTransaction() throws Exception {
		if (getEnv() != null && !isInTransaction()) {
			// TransactionConfig txnConfig = new TransactionConfig();
			@SuppressWarnings("unused")
			Transaction txn = getEnv().beginTransaction(null, null);
		} else {
			throw new NullPointerException(
					"startTransaction called with EntityManager null");
		}
	}

	public Iterator<Object> openByQuery(Class<?> aClass, String aSql,
			Object[] aArguments) throws Exception {
		return null;
	}

	public Iterator<Object> openByQuery(String aSql, Object[] aArguments)
			throws Exception {
		return null;
	}

	public void deleteAll(Class<?> aClass) throws Exception {
		System.out.println("not implemented yet");
	}

	private Environment getEnv() {
		return berkeleyBase.getEnvironment();
	}

	public PersistenceType technology() {
		return PersistenceType.BERKELEY;
	}

	private void logError(String msg) {
		System.out.println(msg);
	}

}
